package com.we.wfc.system.dto;

import com.google.common.collect.Lists;
import com.we.wfc.common.utils.CommonUtil;
import com.we.wfc.system.entity.Area;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * 行政区划 查询 Dto
 *
 * @author zhangby
 * @date 4/1/20 4:59 pm
 */
@Data
@Accessors(chain = true)
public class AreaQueryDto {
    private String parentId;
    private String keyword;

    /**
     * 设置查询条件
     */
    public Specification<Area> buildQuery() {

        Specification<Area> specification = (root, query, cb) -> {
            List<Predicate> predicateList = Lists.newArrayList();
            //条件判断
            CommonUtil.emptyStr(parentId).ifPresent(key ->
                    predicateList.add(
                            cb.equal(root.get("parentId").as(String.class), parentId)
                    )
            );
            // 模糊查询
            CommonUtil.emptyStr(keyword).ifPresent(key ->
                    predicateList.add(
                            cb.or(
                                    cb.like(root.get("name").as(String.class), "%" + keyword + "%"),
                                    cb.like(root.get("shortName").as(String.class), "%" + keyword + "%"),
                                    cb.like(root.get("code").as(String.class), "%" + keyword + "%")
                            )
                    )
            );
            return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
        };

        return specification;
    }

}
